#!/usr/bin/env python
# coding: utf-8


import logging
import re
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
from config.config import configs


class MailUtils(object):
    """
    邮件服务　工具类
    """

    from_addr = configs["email_server"]["from_addr"]
    password = configs["email_server"]["password"]
    to_addr = configs["email_server"]["to_addr"]
    smtp_server = configs["email_server"]["smtp_server"]

    @staticmethod
    def _format_addr(name_addr):
        """

        :param name_addr:
        :return:
        """
        name, addr = parseaddr(name_addr)
        return formataddr((Header(name, 'utf-8').encode(),
                           addr.encode('utf-8') if isinstance(addr, unicode) else addr))

    @classmethod
    def send_mail_to(cls, message, subject):
        """

        :param message:
        :param subject:
        :return:
        """

        if not cls.verify_email():
            return

        msg = MIMEText(message, 'plain', 'utf-8')
        msg['From'] = cls._format_addr('server <%s>' % cls.from_addr)
        msg['To'] = cls._format_addr('developer <%s>' % cls.to_addr)
        msg['Subject'] = Header(subject, 'utf-8').encode()

        server = smtplib.SMTP(cls.smtp_server, 25)
        server.set_debuglevel(1)
        try:
            server.login(cls.from_addr, cls.password)
        except Exception as ex:
            logging.error('Email login Failed! {0}'.format(ex))
            return

        server.sendmail(cls.from_addr, cls.to_addr, msg.as_string())
        server.quit()

    @classmethod
    def verify_email(cls):
        """
        验证邮箱格式
        :return:
        """

        rex = r'''[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?'''
        verify = True
        if not re.findall(rex, cls.from_addr):
            logging.error('Sender email error, {0}.'.format(cls.from_addr))
            verify = False

        if not re.findall(rex, cls.to_addr):
            logging.error('Accepter email error, {0}.'.format(cls.to_addr))
            verify = False

        return verify
